import http from '@/utils/request';
import { user, routes, systemConfig,theme } from '@/store';
import { Session } from '@/utils/storage';
import { decryptSM4,encryptSM4 } from '@/utils/util';
import router from '@/router';
import Watermark from '@/utils/watermark';
const VITE_API_URL = import.meta.env.VITE_API_URL as string;
const VITE_FILE_API_URL = import.meta.env.VITE_FILE_API_URL as string;
const VITE_FILE_CLIENT_ID = import.meta.env.VITE_FILE_CLIENT_ID as string;
const LOCAL_TOKEN_NAME = import.meta.env.VITE_LOCAL_TOKEN_NAME as string;
const VITE_CHANGEPWD_NAME = import.meta.env.VITE_CHANGEPWD_NAME as string;
const LOCAL_REFRESHTOKEN_NAME = import.meta.env.VITE_LOCAL_REFRESHTOKEN_NAME as string;
const LOGIN_PATH = import.meta.env.VITE_LOGIN_PATH as string;
const ROOT_ROUTER_ID = import.meta.env.VITE_ROOT_ROUTER_ID as string;
const VITE_REFRESH_TOKEN = import.meta.env.VITE_REFRESH_TOKEN as string;
const VITE_APP_ID = import.meta.env.VITE_APP_ID as string;
const VITE_SIGN_ENANLED = import.meta.env.VITE_SIGN_ENANLED as string;
const VITE_CRYPTO_ENANLED= import.meta.env.VITE_CRYPTO_ENANLED as string;
const COMMON_URL = '/doc/api/';
export default {
	send: {
		url: `${VITE_API_URL}` + COMMON_URL,
		name: '根据funcCode调用方法',
		postCrypto: async function (funcCode: string, data: object, timeout: number,repeatEnabled:boolean,desensitizeFlag:boolean) {
			//加密接口
			return this.post(funcCode,data,timeout,true,repeatEnabled,desensitizeFlag);
		},
		postRepeat: async function (funcCode: string, data: object, timeout: number,cryptoEnabled:boolean,desensitizeFlag:boolean) {
			//防重复提交接口
			return this.post(funcCode,data,timeout,cryptoEnabled,true,desensitizeFlag);
		},
		post: async function (funcCode: string, data: object, timeout: number,cryptoEnabled:boolean,repeatEnabled:boolean,desensitizeFlag:boolean) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': funcCode,'x-desensitize-flag':desensitizeFlag+'',cryptoEnabled:cryptoEnabled+'',repeatEnabled:repeatEnabled+'' };
			config.headers = headers;
			return await http.post(this.url + funcCode, data, config);
		},
		getCrypto: async function (funcCode: string, data: object, timeout: number,repeatEnabled:boolean,desensitizeFlag:boolean) {
			//加密接口
			return this.get(funcCode,data,timeout,true,repeatEnabled,desensitizeFlag);
		},
		getRepeat: async function (funcCode: string, data: object, timeout: number,cryptoEnabled:boolean,desensitizeFlag:boolean) {
			//防重复提交接口
			return this.get(funcCode,data,timeout,cryptoEnabled,true,desensitizeFlag);
		},
		get: async function (funcCode: string, data: object, timeout: number,cryptoEnabled:boolean,repeatEnabled:boolean,desensitizeFlag:boolean) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': funcCode,'x-desensitize-flag':desensitizeFlag+'',cryptoEnabled:cryptoEnabled+'',repeatEnabled:repeatEnabled+'' };
			config.headers = headers;
			return await http.get(funcCode, data, config);
		},
	},
	fileSend: {
		url: `${VITE_FILE_API_URL}` + COMMON_URL,
		name: '根据funcCode调用文件服务方法',
		post: async function (funcCode: string, data: object, timeout: number) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': funcCode };
			config.headers = headers;
			return await http.post(this.url + funcCode, data, config);
		},
	},
	download: {
		url: `${VITE_API_URL}` + COMMON_URL,
		name: '下载文件方法',
		post: function (funcCode: string, data: object, fileName: string, timeout: number) {
			return http.downloadFile(this.url + funcCode, fileName, data, 'post', timeout);
		},
		postUrl: function (url: string, data: object, fileName: string, timeout: number) {
			return http.downloadFile(url, fileName, data, 'post', timeout);
		},
		get: function (funcCode: string, fileName: string, data: object, timeout: number) {
			return http.downloadFile(this.url + funcCode, fileName, data, 'get', timeout);
		},
		getUrl: function (url: string, fileName: string, data: object, timeout: number) {
			return http.downloadFile(url, fileName, data, 'get', timeout);
		},
	},
	getBatchDict: {
		funcCode: 'dict0013',
		url: `${VITE_API_URL}` + COMMON_URL + 'dict0013',
		name: '批量获取数据字典信息',
		post: async function (data: object, timeout: number) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': 'dict0013' };
			config.headers = headers;
			return await http.post(this.url, data, config);
		},
	},
	getDict: {
		funcCode: 'dict0012',
		url: `${VITE_API_URL}` + COMMON_URL + 'dict0012',
		name: '单个获取数据字典信息',
		post: async function (data: object, timeout: number) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': 'dict0012' };
			config.headers = headers;
			return await http.post(this.url, data, config);
		},
	},
	getDictCondition: {
		funcCode: 'dict0021',
		url: `${VITE_API_URL}` + COMMON_URL + 'dict0021',
		name: '单个获取过滤条件字典下拉信息',
		post: async function (data: object, timeout: number) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': 'dict0021' };
			config.headers = headers;
			return await http.post(this.url, data, config);
		},
	},
	getDictSearchData: {
		funcCode: 'dict0022',
		url: `${VITE_API_URL}` + COMMON_URL + 'dict0022',
		name: '获取通用搜索数据',
		post: async function (data: object, timeout: number) {
			let config: any = {};
			if (timeout && timeout > 0) {
				config.timeout = timeout;
			}
			let headers = { 'func-code': 'dict0022',cryptoEnabled:true };
			config.headers = headers;
			return await http.post(this.url, data, config);
		},
	},
	fileUploadUrl: {
		url: `${VITE_FILE_API_URL}/api/common/file/upload/${VITE_FILE_CLIENT_ID}`,
		name: '上传文件url',
	},
	fileShowUrl: {
		url: `${VITE_FILE_API_URL}/api/common/file/show/${VITE_FILE_CLIENT_ID}/`,
		name: '查看文件url',
	},
	fileDownloadUrl: {
		url: `${VITE_FILE_API_URL}/api/common/file/download/${VITE_FILE_CLIENT_ID}/`,
		name: '下载文件url',
	},
	fileDeleteUrl: {
		url: `${VITE_FILE_API_URL}/api/common/file/delete/${VITE_FILE_CLIENT_ID}/`,
		name: '删除文件',
	},
	login: {
		funcCode: 'login0001',
		url: `${VITE_API_URL}` + COMMON_URL + 'login0001',
		name: '登录',
		post: async function (data: object) {
			let config: any = {};
			let headers = { 'func-code': 'login0001',cryptoEnabled:'true',repeatEnabled:'true' };
			config.headers = headers;
			let params=Object.assign({loginAppId:VITE_APP_ID}, data);
			let response = await http.post(this.url, params, config);
			if (response.code === 0) {
				const result = response.result;
				Session.set(LOCAL_TOKEN_NAME, result.accessToken);
				Session.set(VITE_CHANGEPWD_NAME, result.longTimeNoChange);
				Session.set(LOCAL_REFRESHTOKEN_NAME, result.refreshToken);
				await user.setUser(null);
				if(result.secretKey){
					Session.set('USERSECRET',encryptSM4(JSON.stringify(result.secretKey),systemConfig.defaultSM4Key));
				}
				await user.setUserSecret(result.secretKey);
				user.loginTime = result.loginTime;
				user.loginIp = result.loginIp;
				Session.set('bifang_loginTime', result.loginTime);
				Session.set('bifang_loginIp', result.reqIp);
				await user.setRouters([]);
				return true;
			} else {
				return false;
			}
		},
	},
	chooseUser:{
		funcCode: 'login0011',
		url: `${VITE_API_URL}` + COMMON_URL + 'login0011',
		name: '切换登录',
		post: async function (data: object) {
			let config: any = {};
			let headers = { 'func-code': 'login0011',cryptoEnabled:'true' };
			headers[VITE_REFRESH_TOKEN]=Session.get(LOCAL_REFRESHTOKEN_NAME);
			config.headers = headers;
			let params=Object.assign({loginAppId:VITE_APP_ID}, data);
			let response = await http.post(this.url, params, config);
			if (response.code === 0) {
				const result = response.result;
				Session.set(LOCAL_TOKEN_NAME, result.accessToken);
				Session.set(LOCAL_REFRESHTOKEN_NAME, result.refreshToken);
				await user.setUser(null);
				if(result.secretKey){
					Session.set('USERSECRET',encryptSM4(JSON.stringify(result.secretKey),systemConfig.defaultSM4Key));
				}
				await user.setUserSecret(result.secretKey);
				user.loginTime = result.loginTime;
				user.loginIp = result.loginIp;
				Session.set('bifang_loginTime', result.loginTime);
				Session.set('bifang_loginIp', result.reqIp);
				await user.setRouters([]);
				await routes.setRoutesList([]);
				return true;
			} else {
				return false;
			}
		},
	},
	logout: {
		funcCode: 'login0003',
		url: `${VITE_API_URL}` + COMMON_URL + 'login0003',
		name: '用户退出',
		post: async function () {
			let config: any = {};
			let headers = { 'func-code': 'login0003',cryptoEnabled:'true',repeatEnabled:'true' };
			config.headers = headers;
			let params={} as any;
			params[VITE_REFRESH_TOKEN]=Session.get(LOCAL_REFRESHTOKEN_NAME);
			await http.post(this.url, params, config);
			await user.setUser(null);
			await routes.setRoutesList([]);
			Session.clear();
			router.replace({ path: LOGIN_PATH });
		},
	},
	getUserInfo: {
		funcCode: 'base0001',
		url: `${VITE_API_URL}` + COMMON_URL + 'base0001',
		name: '获取登录用户信息',
		post: async function () {
			//先从session中获取，获取不到再调用接口获取
			let userInfo = await Session.get('USER_INFO');
			if (userInfo) {
				try{
					let info=JSON.parse(decryptSM4(userInfo,systemConfig.defaultSM4Key))
					await user.setUser(info);
					Watermark.set('') ;

					if(info.secretKey){
						await user.setUserSecret(info.secretKey);
					}

				}catch(error){
					await user.setUser(userInfo);
					Watermark.set('') ;
					if(userInfo.secretKey){
						Session.set('USERSECRET',encryptSM4(JSON.stringify(userInfo.secretKey),systemConfig.defaultSM4Key));
						await user.setUserSecret(userInfo.secretKey);
					}
				}
				return true;
			} else {
				let params: any = {};
				params.token = Session.get(LOCAL_TOKEN_NAME);
				let config: any = {};
				let headers = { 'func-code': 'base0001',cryptoEnabled:'true' };
				config.headers = headers;
				let response = await http.post(this.url, params, config);
				if (response.code === 0) {
					const result = response.result;
					if (result) {
						await user.setUser(result);
						Watermark.set('') ;
						if(result.secretKey){
							Session.set('USERSECRET',encryptSM4(JSON.stringify(result.secretKey),systemConfig.defaultSM4Key));
							await user.setUserSecret(result.secretKey);
						}
						Session.set('USER_INFO', encryptSM4(JSON.stringify(result),systemConfig.defaultSM4Key));
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			}
		},
	},
	getUserInfoEn: {
		funcCode: 'base0016',
		url: `${VITE_API_URL}` + COMMON_URL + 'base0016',
		name: '获取登录用户信息',
		post: async function () {
			let userInfo = await Session.get('USER_INFO');
			if (userInfo) {
				try{
					let info=JSON.parse(decryptSM4(userInfo,systemConfig.defaultSM4Key))
					await user.setUser(info);
					Watermark.set('') ;
					if(info.secretKey){
						await user.setUserSecret(info.secretKey);
					}

				}catch(error){
					await user.setUser(userInfo);
					Watermark.set('') ;
					if(userInfo.secretKey){
						Session.set('USERSECRET',encryptSM4(JSON.stringify(userInfo.secretKey),systemConfig.defaultSM4Key));
						await user.setUserSecret(userInfo.secretKey);
					}
				}
				return true;
			} else {
				let params: any = {};
				params.token = encryptSM4(Session.get(LOCAL_TOKEN_NAME),systemConfig.defaultSM4Key);
				let config: any = {};
				let headers = { 'func-code': 'base0016',cryptoEnabled:'true' };
				config.headers = headers;
				let response: any = await http.post(this.url, params, config);
				if (response.code === 0) {
					const result = response.result;
					if (result) {
						await user.setUser(JSON.parse(decryptSM4(result,systemConfig.defaultSM4Key)));
						Watermark.set('') ;
						Session.set('USER_INFO', result);
						if(result.secretKey){
							Session.set('USERSECRET',encryptSM4(JSON.stringify(result.secretKey),systemConfig.defaultSM4Key));
							await user.setUserSecret(result.secretKey);
						}
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			}
		},
	},
	getMenu: {
		funcCode: 'router0007',
		url: `${VITE_API_URL}` + COMMON_URL + 'router0007',
		name: '获取菜单',
		post: async function (): Promise<boolean> {
			let apiMenu = await Session.get('ROUTERS');
			if (!apiMenu || apiMenu.length <= 0) {
				let params = { routerId: '' };
				params.routerId = ROOT_ROUTER_ID;
				let config: any = {};
				let headers = { 'func-code': 'router0007',cryptoEnabled:'true' };
				config.headers = headers;
				config.timeout=20000;
				let response = await http.post(this.url, params, config);
				if (response.code === 0) {
					const result = response.result;
					if (result && result.length > 0) {
						apiMenu = result;
					}
				}
			}
			Session.set('ROUTERS', apiMenu);
			await user.setRouters(apiMenu);
			return true;
		},
	},
	setAppSecretKey: {
		funcCode: 'base0017',
		url: `${VITE_API_URL}` + COMMON_URL + 'base0017',
		name: '设置应用的秘钥',
		post: async function () {
			if(JSON.parse(VITE_SIGN_ENANLED)||JSON.parse(VITE_CRYPTO_ENANLED)){
				let config: any = {};
				let headers = { 'func-code': 'base0017',repeatEnabled:'true' };
				config.headers = headers;
				await http.post(this.url, {appId: encryptSM4(VITE_APP_ID,systemConfig.defaultSM4Key)}, config);
				Session.set("setAppCryptoFlag","true");
			}
		},
	},
	refreshAccessToken: {
		funcCode: 'base0018',
		url: `${VITE_API_URL}` + COMMON_URL + 'base0018',
		name: '刷新accessToken',
		post: async function () {
			let config: any = {};
			let headers = { 'func-code': 'base0018',cryptoEnabled:'true',repeatEnabled:'true' };
			config.headers = headers;
			let params={} as any;
			params[VITE_REFRESH_TOKEN]=Session.get(LOCAL_REFRESHTOKEN_NAME);
			let res=await http.post(this.url, params, config);
			if (res.code === 0) {
				const result = res.result;
				Session.set(LOCAL_TOKEN_NAME, result.accessToken);
				Session.set(LOCAL_REFRESHTOKEN_NAME, result.refreshToken);
				if(result.secretKey){
					Session.set('USERSECRET',encryptSM4(JSON.stringify(result.secretKey),systemConfig.defaultSM4Key));
				}
				
				await user.setUserSecret(result.secretKey);
				return true;
			} else {
				return false;
			}
		},
	},
};
